// 项目搭建需要用的方法
import MD5 from 'md5'

const { VITE_APPSECRET: APPSECRET } = import.meta.env

/**
 * 模拟 sort 排序 (解决 Safari 下 soft 的 BUG)
 * @param  {Array}   array 需要排序的数组
 * @param  {Function} fn   排序函数
 * @return {Array}         返回排序后的数组
 */
export const _sort = (array: any, fn: any) => {
  for (var i = 0; i < array.length - 1; i++) {
    var isSorted = true
    for (var j = 0; j < array.length - 1 - i; j++) {
      if (fn(array[j], array[j + 1]) > 0) {
        var temp = array[j]
        array[j] = array[j + 1]
        array[j + 1] = temp
        isSorted = false
      }
    }
    if (isSorted) {
      return false
    }
  }
}

export const __objSort = (res: any) => {
  var str = []
  // var obj = {}
  // 将对象转成数组
  for (var i in res) {
    str.push([i, res[i]])
  }
  // 对数组进行排序
  _sort(str, function (a: any, b: any) {
    return a[0] > b[0]
  })
  // 然后转成对象
  // for (let i = 0; i < str.length; i++) {
  //   obj[str[i][0]] = str[i][1]
  // }
  return str
}

export const __joinObj = (res: any) => {
  let objs = __objSort(res)
  let strs = ''
  for (let i = 0; i < objs.length; i++) {
    strs += objs[i][0] + '' + ((objs[i][1] === null || objs[i][1] === undefined) ? '' : objs[i][1])
  }
  strs = MD5(APPSECRET + strs + APPSECRET).toLowerCase()
  return strs
}

/**
 * 生成随机id,三位随机数+时间戳
 */
export const randomId = () => {
  return Math.round(Math.random()) + Date.now()
}

/**
 * 生成uuid
 */
export const nonceStr = () => {
  const s = []
  var hexDigits = '0123456789abcdef'
  for (var i = 0; i < 36; i++) {
    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1)
  }
  s[14] = '4'
  s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1)
  s[8] = s[13] = s[18] = s[23] = '-'

  return s.join('')
}
